<template>
  <div ref="root_node"
       class="wait-gamer">
  </div>
</template>
<script>
import {
  ROOM_STATUS,
  PLAYER_STATUS,
  roomStatusToString,
  playerStatusToString,
} from '../../STATUS';
import render_player, { init_loader as render_player_init_loader } from './render_player';
import { stageComponentGenerator } from '../../core/componentGenerator';
export default stageComponentGenerator({
  name: 'wait-gamer',
  data() {
    return {
      ROOM_STATUS,
      PLAYER_STATUS,
      is_show_continue_dialog: true,
    }
  },
  created() {
    const {
      unwatchers,
      app,
      loader
    } = this;
    loader.add("to_ready", "game/ready_01.png");
    loader.add("to_ready_hover", "game/ready_02.png");
    loader.add("leave", "home/bisaileave.png");
    loader.add("confirm_dialog", "home/bisai_tip.png");
    loader.add("yes_btm", "home/Confirm_01.png");
    loader.add("no_btm", "home/Cancel_01.png");

    loader.add("mode_suffix", "home/人模式.png")
    loader.add("times_prefix", "home/jushu.png")
    loader.add("times_suffix", "home/ju.png")
    loader.add("roomid_prefix", "home/fanghao.png");

    loader.add("continue_btm", "game/xufei_01.png");
    loader.add("leave_btm", "game/likai_01.png");
    // loader.add("share_btm", "game/fengxiang_01.png");

    loader.add("renewals_btm", "game/xufei_03.png");
    // 分享
    loader.add("share_tip", "home/分享_02.png");

    loader.initNumbers();
    render_player_init_loader(loader);

    loader.onError.add(err => console.error(err))
    this.draw_app = async () => {
      console.log("DRAW WAITGAMER");
      const loader = this.loader;
      if (!loader) {// maybe run on after destroyed
        return
      }
      this.clearWatch();
      const resources = loader.resources;
      app.stage.destroy();
      app.stage = new PIXI.Container();
      const stage = new PIXI.Container();
      const top_layer = new PIXI.Container();
      app.stage.addChild(stage);
      app.stage.addChild(top_layer);
      const {
        width,
        height
      } = app.renderer;
      const bg = new PIXI.Sprite(resources.bg.texture);
      bg.width = width;
      bg.height = height;
      stage.addChild(bg);

      const {
        avatar_box_bounds
      } = await render_player.call(this, {
          app,
          stage,
          resources,
          width,
          height,
          unwatchers,
        });

      // 房间信息
      const infoFontSize = avatar_box_bounds.width / 4;
      const text_style = {
        fontSize: infoFontSize,
        fill: 0xFFFFFF
      };
      const $info = new PIXI.Container();
      stage.addChild($info);

      /* 房间信息*/
      unwatchers[unwatchers.length] = this.$watch("room", room => {
        $info.children.slice().forEach($c => $c.destroy());
        // const $mode = new PIXI.Text(`模式：${this.room.player_number}人`, text_style);
        const $mode = new PIXI.Container();
        {
          const $mode_values = loader.getNumberSprite(this.room.player_number)
          $mode_values.maxHeight(infoFontSize);
          $mode.addChild($mode_values);
          const $mode_suffix = new PIXI.Sprite(resources.mode_suffix.texture);
          $mode_suffix.maxHeight(infoFontSize);
          $mode_suffix.x = $mode_values.x + $mode_values.width + infoFontSize / 2;
          $mode.addChild($mode_suffix);
        }
        // const $times = new PIXI.Text(`局数：${room.cur_round}/${room.max_round}局`, text_style);
        const $times = new PIXI.Container();
        {
          const $times_prefix = new PIXI.Sprite(resources.times_prefix.texture);
          $times_prefix.maxHeight(infoFontSize);
          $times.addChild($times_prefix);
          const $times_values = loader.getNumberSprite(`${Math.min(room.max_round - room.cur_round + 1, room.max_round)}/${room.max_round}`)
          $times_values.x = $times_prefix.x + $times_prefix.width + infoFontSize / 2;
          $times_values.maxHeight(infoFontSize);
          $times.addChild($times_values);
          const $times_suffix = new PIXI.Sprite(resources.times_suffix.texture);
          $times_suffix.maxHeight(infoFontSize);
          $times_suffix.x = $times_values.x + $times_values.width + infoFontSize / 2;
          $times.addChild($times_suffix);
        }
        $times.y = $mode.y + $mode.height * 1.5;
        // const $roomid = new PIXI.Text(`房号：${room.id}`, text_style);
        const $roomid = new PIXI.Container();
        {
          const $roomid_prefix = new PIXI.Sprite(resources.roomid_prefix.texture);
          $roomid_prefix.maxHeight(infoFontSize);
          $roomid.addChild($roomid_prefix);
          const $roomid_values = loader.getNumberSprite(room.id)
          $roomid_values.x = $roomid_prefix.x + $roomid_prefix.width + infoFontSize / 2;
          $roomid_values.maxHeight(infoFontSize);
          $roomid.addChild($roomid_values);
        }
        $roomid.y = $times.y + $times.height * 1.5;
        $info.addChild($mode);
        $info.addChild($times);
        $info.addChild($roomid);
        // 定位
        $info.x = infoFontSize;
        $info.y = height - $info.height - infoFontSize;

      }, { immediate: true });
      /*续费对话框*/
      if (this.room.mode === "消费建房") {
        const confirm_dialog_config = {
          parent: top_layer,
          view_width: width,
          view_height: height,
          dialog_texture: resources.confirm_dialog.texture,
          yes_texture: resources.yes_btm.texture,
          no_texture: resources.no_btm.texture,
          open: false,
        };
        let $confirm_1;
        // 房卡耗完，通知房主是否要续费还是解散
        for (let watch_key of ["room", "player.info.cards"]) {
          unwatchers[unwatchers.length] = this.$watch(watch_key, () => {
            const cards = this.player.info.cards;
            const room = this.room;
            console.log("$confirm_1", $confirm_1);

            const confirm_dialog_renderer = async (dialog_parent, { parent_width, parent_height, dialog_width, dialog_height, dialog_content_height }) => {
              // "当前房间可用回合数已经消耗完， 是否使用1张房卡续费房间继续游戏？ 否则直接解散房间。"
              const avatar_parent = new PIXI.Container();
              dialog_parent.addChild(avatar_parent);

              let players = this._statistics_players;
              if (!players) {
                players = await this.getRoomStatistics();
              }

              avatar_parent.children.slice().forEach($c => $c.destroy());
              const player_number = players.length;
              const unit_width = (dialog_width / (player_number * 2 + 0.5));
              console.log("dialog_width", dialog_width)
              players.forEach((player, i) => {
                const parent = new PIXI.Container();
                const $avatar_box = new PIXI.Sprite(resources.avatar_box.texture);
                // $avatar_box.maxWidth(unit_width);
                $avatar_box.maxWidthHeight(unit_width, dialog_content_height / 2);
                const avatar_box_bounds = $avatar_box.getBounds();
                parent.addChild($avatar_box);
                const info = player.info;
                const { headimgurl, username } = info;
                const player_id = this.player.id;
                const $userhead = new PIXI.Sprite.fromImage(`${server_href}/proxy?src=${encodeURIComponent(headimgurl)}`);
                $userhead.id = window.$userhead_id = (window.$userhead_id | 0) + 1;
                const $userhead_texture = $userhead.texture
                $userhead_texture.on("update", function update(tex, is_keep) {
                  $userhead.width = avatar_box_bounds.width * 0.76
                  $userhead.height = $userhead.width;
                  $userhead.x = avatar_box_bounds.width / 2 - $userhead.width / 2;
                  $userhead.y = avatar_box_bounds.height / 2 - $userhead.height / 2 - avatar_box_bounds.height * 0.025;
                  if (!is_keep) {
                    $userhead_texture.off("update", update);
                  }
                });
                $userhead_texture.emit("update", null, !$userhead_texture.valid);

                const fontSize = avatar_box_bounds.height / 7;

                const $username = new PIXI.Text(username, {
                  fontSize: fontSize,
                  fill: 0xFFFFFF
                });
                $username.alpha = 0.9;
                // $username.x = $userhead.x + $userhead.width + 5;
                $username.x = avatar_box_bounds.width / 2 - $username.width / 2;
                $username.y = fontSize * 0.1;

                parent.addChildBefore($userhead, $avatar_box);
                parent.addChildAfter($username, $avatar_box);

                parent.x = dialog_width / (player_number + 1) * (i + 1) - avatar_box_bounds.width / 2;
                parent.y = dialog_content_height * 0.1;

                parent.showText = ($txt) => {
                  if (parent._cache_$txt) {
                    parent._cache_$txt.destroy();
                    // parent._cache_$txt = null;
                  }
                  $txt.x = avatar_box_bounds.width / 2 - $txt.width / 2;
                  $txt.y = avatar_box_bounds.height * 0.85 - $txt.height / 2;
                  parent._cache_$txt = $txt;
                  parent.addChildAfter($txt, $avatar_box);
                };

                let total_fill = 0xdddddd;
                if (player.total > 0) {
                  total_fill = 0x00FF00;
                } else if (player.total < 0) {
                  total_fill = 0xFF0000;
                }
                const $player_total = new PIXI.Text(player.total, {
                  fontSize,
                  fill: total_fill,
                });
                parent.showText($player_total);
                avatar_parent.addChild(parent);
              });

              // 房间续费提示
              const $continue_info = new PIXI.Text("", {
                fontSize: Math.min(dialog_width, dialog_height) / 20,
                fill: 0xFFFFFF,
                wordWrap: true,
                wordWrapWidth: dialog_width * 0.9,
                dropShadow: true,
                dropShadowBlur: 5,
                dropShadowDistance: 2,
                dropShadowColor: 0x2233FF,
                // fill: [0xd276e5, 0xf2a6ff],
              });
              dialog_parent.addChild($continue_info);
              if (room.cur_round === 0) {
                if (cards >= 1) {
                  $continue_info.text = "当前房间可用回合数已经消耗完， 是否使用1张房卡续费房间继续游戏？"
                } else {
                  $continue_info.text = "当前房间可用回合数已经消耗完， 您的房卡已经不足以续费房间。 您可以让您的朋友消耗房卡仅需游戏； 或者临时关掉网页， 联系管理员进行房卡充值后， 回到房间继续当前房间的游戏。"
                  $continue_info.style.fontSize = Math.min(dialog_width, dialog_height) / 24;
                }
              } else {
                $continue_info.text = "房间已续费， 点击确定继续游戏。"
              }

              $continue_info.x = dialog_width / 2 - $continue_info.width / 2;
              $continue_info.y = dialog_content_height * 3 / 4 - $continue_info.height / 2;

            };

            if (room.cur_round === 0 && room.owner) {//&& this.room.owner.id === this.player.id
              // if (this.player.info.cards >= 1) {
              if ($confirm_1) {
                $confirm_1.destroy();
                $confirm_1 = null;
              }

              $confirm_1 = new PIXI.Confirm(confirm_dialog_renderer, Object.assign(confirm_dialog_config, {
                yes_texture: resources.renewals_btm.texture,
                no_texture: resources.leave_btm.texture,
              })).on("close", res => {
                if (res) {
                  this.is_show_continue_dialog = false;
                  this.rechargeRoom();
                } else {
                  this.leaveRoom();
                }
                // 回退微信分享的配置
                wx_promise.then(function (wx) {
                  wx.onMenuShareAppMessage(window._wx_onMenuShareAppMessage_config);
                });

              });

              wx_promise.then(function (wx) {
                // 分享信息
                const share_tip = new PIXI.Container();
                $confirm_1.addChild(share_tip);
                const share_tip_content = new PIXI.Sprite(resources.share_tip.texture);
                share_tip_content.maxWidthHeight(width * 0.5 / 2, height * 0.3 / 2);
                share_tip_content.x = width - share_tip_content.width;
                share_tip_content.y = 0;
                share_tip.addChild(share_tip_content);
                const share_text = new PIXI.Text("点击分享，\n可以直接分享\n本轮游戏的统计结果", {
                  fill: 0xFFFFFF,
                  fontSize: share_tip_content.width / 6,
                  align: "center"
                });
                share_text.x = share_tip_content.x - share_text.width * 0.7;
                share_text.y = share_tip_content.y + share_tip_content.height;
                share_tip.addChild(share_text);

                wx.onMenuShareAppMessage({
                  title: '闽游十三水', // 分享标题
                  desc: `最正宗的闽南十三水！房号:${room.id}游戏统计结果`, // 分享描述
                  link: `http://13shui.youdob.org/tool/results.html?room_hash_id=${encodeURIComponent(room.hash_id)}`, // 分享链接
                  imgUrl: `http://${location.host}/static/logo.128x128.png`, // 分享图标
                  type: '', // 分享类型,music、video或link，不填默认为link
                  dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                  success: function () {
                    // 用户确认分享后执行的回调函数
                    // alert("share success")
                  },
                  cancel: function () {
                    // 用户取消分享后执行的回调函数
                    // alert("share error")
                  }
                });
              })

              if (cards >= 1) {
                $confirm_1.yes_button.texture = resources.continue_btm.texture;
                $confirm_1.yes_button.interactive = true;
              } else {
                $confirm_1.yes_button.texture = resources.renewals_btm.texture
                $confirm_1.yes_button.interactive = false;
              }
              $confirm_1.open();
            } else {
              if ($confirm_1) {
                $confirm_1.destroy();
                $confirm_1 = null;
                if (this.__close_confirm_1) {
                  return;
                }
                // 如果窗口打开过，说明房间已经续费过，那么改变窗口功能按钮，
                $confirm_1 = new PIXI.Alert(confirm_dialog_renderer, Object.assign(confirm_dialog_config, {
                  yes_texture: resources.yes_btm.texture,
                })).on("close", () => {
                  this.__close_confirm_1 = true;
                  $confirm_1.close();
                  // 回退微信分享的配置
                  wx_promise.then(function (wx) {
                    wx.onMenuShareAppMessage(window._wx_onMenuShareAppMessage_config);
                  });
                });
                $confirm_1.open();
              }
            }
          }, { immediate: true });
        }
      }
      // 邀请好友加入房间

      let _pre_share_room_link = "";
      unwatchers[unwatchers.length] = this.$watch("room", () => {
        const room = this.room;
        if (room && room.owner && room.mode === "消费建房" && room.hash_id && room.cur_round !== 0) {

          const query = queryString.parse();
          const new_query = Object.assign({}, query, {
            share_code: this.player.id,
            room: room.id,
            room_hash_id: room.hash_id,
          });
          delete new_query.u;
          const share_room_link = `http://${location.host}${location.pathname}?${queryString.stringify(new_query)}`; // 分享链接
          if (share_room_link === _pre_share_room_link) {
            return
          }
          _pre_share_room_link = share_room_link;
          wx_promise.then(wx => {
            if (_pre_share_room_link !== share_room_link) {
              return
            }
            wx.onMenuShareAppMessage({
              title: '闽游十三水', // 分享标题
              desc: `快来试试手气！${room.player_number}人模式，房号${room.id}`, // 分享描述
              link: share_room_link,
              imgUrl: `http://${location.host}/static/logo.128x128.png`, // 分享图标
              type: '', // 分享类型,music、video或link，不填默认为link
              dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
              success: function () {
                // 用户确认分享后执行的回调函数
                // alert("share success")
              },
              cancel: function () {
                // 用户取消分享后执行的回调函数
                // alert("share error")
              }
            });
          });

        }
      }, { immediate: true });

      const $user_info = new PIXI.Container();
      stage.addChild($user_info);
      unwatchers[unwatchers.length] = this.$watch("player.info", user_info => {
        $user_info.children.slice().forEach($c => $c.destroy());
        const $cards = new PIXI.Text(`房卡：${user_info.cards || 0}张`, text_style);
        const $points = new PIXI.Text(`水豆：${user_info.points || 0}颗`, text_style);
        $points.y = $cards.y + $cards.height * 1.5;
        $user_info.addChild($cards);
        $user_info.addChild($points);
        // 定位
        $user_info.x = width - $user_info.width - infoFontSize;
        $user_info.y = height - $user_info.height - infoFontSize;
      }, { immediate: true });

      // 准备按钮
      const $ready_button = new PIXI.Sprite(resources.to_ready.texture);
      const READY_WIDTH = avatar_box_bounds.width * 2;
      let __ready_button_handle = null;
      $ready_button.bindTap(() => {
        if (this.room.cur_round <= 0) {
          return;
        }
        __ready_button_handle && __ready_button_handle();
      });
      $ready_button.maxWidth(READY_WIDTH);
      $ready_button.x = avatar_box_bounds.x + avatar_box_bounds.width / 2 - $ready_button.width / 2;
      $ready_button.y = avatar_box_bounds.top - $ready_button.height * 1.4;
      stage.addChild($ready_button);
      unwatchers[unwatchers.length] = this.$watch("player.status", (status) => {
        $ready_button.visible = true;
        if (status === PLAYER_STATUS.UN_READY) {
          $ready_button.texture = resources.to_ready.texture
          $ready_button.maxWidth(READY_WIDTH);
          $ready_button.hoverSprite(resources.to_ready_hover.texture);
          __ready_button_handle = this.toReady;
        } else if (status === PLAYER_STATUS.READY) {
          $ready_button.texture = resources.ready.texture
          $ready_button.maxWidth(READY_WIDTH);
          $ready_button.hoverSprite();
          __ready_button_handle = this.toUnReady;
        } else {
          $ready_button.visible = false
          __ready_button_handle = null
        }
      }, { immediate: true });

      // 离开按钮
      const $leave_btm = new PIXI.Sprite(resources.leave.texture);
      $leave_btm.hover(() => $leave_btm.tint = 0x999999, () => $leave_btm.tint = 0xFFFFFF);
      $leave_btm.maxWidth(avatar_box_bounds.width);
      $leave_btm.x = $leave_btm.width * 0.2;
      $leave_btm.y = $leave_btm.width * 0.2;
      stage.addChild($leave_btm);
      $leave_btm.bindTap(() => {
        this.leaveRoom()
      });
    }
  },
  destroyed() {
    wx_promise.then(function (wx) {
      wx.onMenuShareAppMessage(window._wx_onMenuShareAppMessage_config);
    });
  },
  methods: {
    toReady() {
      socket.emit("ready");
    },
    toUnReady() {
      socket.emit("not-ready");
    },
    leaveRoom() {
      socket.emit("leave-room");
    },
    rechargeRoom() {
      socket.emit("recharge-room");
    },
    getRoomStatistics() {
      return new Promise(resolve => {
        socket.emit("statistics-room");
        socket.on("room-statistics-res", players => {
          resolve(this._statistics_players = players)
        })
      });
    },
    roomStatusToString,
    playerStatusToString,
  },
})
</script>
<style>
.wait-gamer {
  width: 100%;
  height: 100%
}
</style>